<template>
  <!-- // 分配角色 -->
  <div>
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getRoles } from '@/api/roles'
import { assignRoles, getUserDetailInfo } from '@/api/user'
export default {
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleIds: [],
      roles: []
    }
  },
  created() {
    this.loadRoles()
    this.loadUserRoles()
  },
  methods: {
    closeDialog() {
      this.$emit('hclose')
    },
    // 获取所有角色列表
    async loadRoles() {
      const res = await getRoles().catch(e => e)
      if (!res.success) return
      // console.log(res)
      this.roles = res.data.rows
    },
    // 根据id获取用户的角色列表
    async loadUserRoles() {
      // 发请求
      const res = await getUserDetailInfo(this.userId)
      if (!res.success) return
      // 数据回写
      this.roleIds = res.data.roleIds
      console.log(res)
    },
    // 点击确定,保存给用户分配的角色
    async hSubmit() {
      const res = await assignRoles({ id: this.userId, roleIds: this.roleIds }).catch(e => e)
      if (!res.success) return
      this.$message.success(res.message)
      // 关闭dialog
      this.$emit('hclose')
    }
  }
}
</script>
